<?php
class Admin_PhotoManagementController extends Apps_Controller_Action_Admin {
	// Set Const
	const TYPE_AVATAR 		= 1;
	const TYPE_THUMBNAIL 	= 2;
	const TYPE_PHOTO 		= 3;


    public function indexAction() {
    	$this->_forward('hotel', null, null);
    }

    // Detail Photo
    public function hotelAction() {
        $rq = $this->_request;
        $hotelId = intval($rq->getParam('id'));
        $tbHotel = new M_DbTable_Hotel();
        $tbArticle = new M_DbTable_Article();
        $tbPhoto   = new M_DbTable_Photo();

        if(null === $hotelId) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
            $this->goToControllerIndex();
        }

        if($rq->getParam('act_delete')) { $this->_forward('photo-delete', null, null, array('id' => $hotelId)); }

        $qAvatar = $this->_dbAdapter
	                  ->select()
	                  ->from('hotel', null)
	                  ->where('hotel.id = ?', $hotelId)
	                  ->columns(array(
	                        'path' => 'hotel.avatar'
	                    ));

        $qThumbnail = $this->_dbAdapter
		                  ->select()
		                  ->from('hotel', null)
		                  ->join('article', 'article.reference_id = hotel.id AND article.reference_type = ' . M_DbTable_Article::REFERENCE_TYPE_HOTEL, null)
		                  ->where('hotel.id = ?', $hotelId)
		                  ->columns(array(
		                  		'path' => 'article.thumbnail'
		                    ));

        $qPhoto = $this->_dbAdapter
	                  ->select()
	                  ->from('hotel', null)
	                  ->join('photo', 'photo.reference_id = hotel.id AND photo.reference_type = ' . M_DbTable_Article::REFERENCE_TYPE_HOTEL, null)
	                  ->where('hotel.id = ?', $hotelId)
	                  ->columns(array(
	                  		'id'		=> 'photo.id',
	                  		'path' 		=> 'photo.path',
	                  		'caption' 	=> 'photo.caption'
	                    ));



        $dAvatar	= $qAvatar->query()->fetch();
        $dThumbnail	= $qThumbnail->query()->fetch();
        $dPhoto		= $qPhoto->query()->fetchAll();

        if ($rq->isPost()) {
            $hotelPhotoTypeId = $rq->getParam('photo_type');

            switch ($hotelPhotoTypeId) {
            	case self::TYPE_AVATAR:
		            if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {

		                $contentFilter = new M_Tool_ContentFilter();
		                $catDir = 'avatar';
		                $catDir = $contentFilter->castViToBoringLower($catDir, true);
		                $catDir = Apps_Plugin_Upload_File::CAT_HOTEL . '/' . $catDir;

		                $uploader = new Apps_Plugin_Upload_File();
		                $uploader->setMaxQuantity(1)
		                         ->setSubCategory($catDir . '/'. $hotelId . '/', true);

		                if($uploaded = $uploader->upload()) {
		                    $thumbnail = $uploaded['thumbnail']['uri'];

		                    //resize images
		                    try {
		                        $image = new Apps_Plugin_ResizeImages();
		                        $image->load(PUBLIC_PATH .$thumbnail);
		                        $image->resizeToWidth(250);
		                        $image->save(PUBLIC_PATH .$thumbnail);
		                    } catch (Exception $e) {
		                        //Excetion here
		                    }
		                }

		                $tbHotel->safelyUpdate(array('avatar' => $thumbnail),
		                					   array('id = ?' => $hotelId));
    		            if($dThumbnail) {
        	        		$this->deletePhoto($dThumbnail['path']);
    	                }
		                $this->refresh(array('id' => $hotelId));
		            }
            		break;

            	case self::TYPE_THUMBNAIL:
		            if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {

		                $contentFilter = new M_Tool_ContentFilter();
		                $catDir = 'thumbnail';
		                $catDir = $contentFilter->castViToBoringLower($catDir, true);
		                $catDir = Apps_Plugin_Upload_File::CAT_HOTEL . '/' . $catDir;

		                $uploader = new Apps_Plugin_Upload_File();
		                $uploader->setMaxQuantity(1)
		                         ->setSubCategory($catDir . '/'. $hotelId . '/', true);

		                if($uploaded = $uploader->upload()) {
		                    $thumbnail = $uploaded['thumbnail']['uri'];

		                    //resize images
		                    try {
		                        $image = new Apps_Plugin_ResizeImages();
		                        $image->load(PUBLIC_PATH .$thumbnail);
		                        $image->resizeToWidth(156);
		                        $image->save(PUBLIC_PATH .$thumbnail);
		                    } catch (Exception $e) {
		                        //Excetion here
		                    }
		                }

		                $r = $tbArticle->safelyUpdate(array('thumbnail' 			=> $thumbnail),
		                					   	 	  array('reference_id = ?' 		=> $hotelId,
		                					   		   	    'reference_type = ?' 	=> M_DbTable_Article::REFERENCE_TYPE_HOTEL));

		                $this->_flashMessenger->addMessage($r ? self::$msgUpdateSuccess : self::$msgUpdateFailed);
    		            if($dThumbnail) {
        	        		$this->deletePhoto($dThumbnail['path']);
    	                }
		                $this->refresh(array('id' => $hotelId));
		            }
            		break;

            	case self::TYPE_PHOTO:
		            if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {

		                $contentFilter = new M_Tool_ContentFilter();
		                $catDir = 'photo';
		                $catDir = $contentFilter->castViToBoringLower($catDir, true);
		                $catDir = Apps_Plugin_Upload_File::CAT_HOTEL . '/' . $catDir;

		                $uploader = new Apps_Plugin_Upload_File();
		                $uploader->setMaxQuantity(1)
		                         ->setSubCategory($catDir . '/'. $hotelId . '/', true);

		                if($uploaded = $uploader->upload()) {
		                    $thumbnail = $uploaded['thumbnail']['uri'];

		                    //resize images
		                    try {
		                        $image = new Apps_Plugin_ResizeImages();
		                        $image->load(PUBLIC_PATH .$thumbnail);
		                        $image->resizeToWidth(250);
		                        $image->save(PUBLIC_PATH .$thumbnail);
		                    } catch (Exception $e) {
		                        //Excetion here
		                    }
		                }

		                $tbPhoto->safelyInsert(array(
		                					'reference_id' 		=> $hotelId,
		                					'reference_type' 	=> M_DbTable_Photo::REFERENCE_TYPE_HOTEL,
		                                    'path' 				=> $thumbnail,
		                					'caption'			=> $rq->getParam('caption')
		                                ));
		                $this->refresh(array('id' => $hotelId));
		            }
            		break;

            	default:
            		$this->_helper->redirector('index', 'hotel', null);
            		break;
            }
        }

        $this->view->dataAvatar 	= $dAvatar;
        $this->view->dataThumbnail 	= $dThumbnail;
        $this->view->dataPhoto 		= $dPhoto;
    }

    public function tourAction() {
        $rq = $this->_request;
        $tourId = intval($rq->getParam('id'));
        $tbtour = new M_DbTable_Tour();
        $tbArticle = new M_DbTable_Article();

        if(null === $tourId) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
            $this->goToControllerIndex();
        }

        $qThumbnail = $this->_dbAdapter
		                  ->select()
		                  ->from('tour', null)
		                  ->join('article', 'article.reference_id = tour.id', null)
		                  ->where('article.reference_type = ?', M_DbTable_Article::REFERENCE_TYPE_TOUR)
		                  ->where('tour.id = ?', $tourId)
		                  ->columns(array(
		                  		'path' => 'article.thumbnail',
		                  		'path_detail' => 'tour.detail_thumbnail'
		                    ));

        $dThumbnail	= $qThumbnail->query()->fetch();

        if ($rq->isPost()) {
            $tourPhotoTypeId = $rq->getParam('photo_type');

           	if($tourPhotoTypeId == self::TYPE_THUMBNAIL) {

           		//upload Thumbnail
            	if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_TOUR);

					$thumbnail = ($uploaded = $uploader->upload())
							 	 ? $uploaded['thumbnail']['uri']
							 	 : null;

					//resize images
					try {
					    $thumbnailNew = str_replace('/tour/', '/tour/thumbnail_', $thumbnail);
					    $image = new Apps_Plugin_ResizeImages();
					    $image->load(PUBLIC_PATH .$thumbnail);
					    $image->resizeToWidth(156);
					    $image->save(PUBLIC_PATH .$thumbnailNew);

					    //detail thumbnail;
					    $detailThumbnail = str_replace('/tour/', '/tour/detail_thumbnail_', $thumbnail);
					    $image->load(PUBLIC_PATH .$thumbnail);
					    $image->resizeToWidth(366);
					    $image->save(PUBLIC_PATH .$detailThumbnail);

					} catch (Exception $e) {
					    //Excetion here
					}

					$where = array('reference_id = ?' 		=> $tourId,
	                		       'reference_type = ?' 	=> M_DbTable_Article::REFERENCE_TYPE_TOUR);

					$r1 = $tbtour->safelyUpdate(array('detail_thumbnail' => $detailThumbnail), array('id=?' => $tourId));
	                $r = $tbArticle->safelyUpdate(array('thumbnail' => $thumbnailNew), $where);

	                $this->_flashMessenger->addMessage($r ? self::$msgUpdateSuccess : self::$msgUpdateFailed);
	                if($dThumbnail) {
    	        		$this->deletePhoto($dThumbnail['path']);
	                }
	                $this->refresh(array('id' => $tourId));
            	}
            }
        }
        $this->view->dataThumbnail 	= $dThumbnail;
    }

    public function cruiseAction() {
        $rq = $this->_request;
        $cruiseId = intval($rq->getParam('id'));
        $tbArticle = new M_DbTable_Article();
        $tbcruiseItineraryTour = new M_DbTable_CruiseItineraryTour();

        if(null === $cruiseId) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
            $this->goToControllerIndex();
        }

        $qThumbnail = $this->_dbAdapter
		                  ->select()
		                  ->from('cruise_itinerary_tour', null)
		                  ->join('article', 'article.reference_id = cruise_itinerary_tour.id', null)
		                  ->where('article.reference_type = ?', M_DbTable_Article::REFERENCE_TYPE_CRUISE)
		                  ->where('cruise_itinerary_tour.id = ?', $cruiseId)
		                  ->columns(array(
		                  		'path' 		  => 'article.thumbnail',
		                  		'path_detail' => 'cruise_itinerary_tour.detail_thumbnail'
		                    ));

        $dThumbnail	= $qThumbnail->query()->fetch();

        if ($rq->isPost()) {
            $cruisePhotoTypeId = $rq->getParam('photo_type');

           	if($cruisePhotoTypeId == self::TYPE_THUMBNAIL) {

           		//upload Thumbnail
           		if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_CRUISE);
					$thumbnail = ($uploaded = $uploader->upload())
							 	 ? $uploaded['thumbnail']['uri']
							 	 : null;

           		    //resize images
					try {
    				    $thumbnailNew = str_replace('/cruise/', '/cruise/thumbnail_', $thumbnail);
						$image = new Apps_Plugin_ResizeImages();
    				    $image->load(PUBLIC_PATH .$thumbnail);
    				    $image->resizeToWidth(156);
    				    $image->save(PUBLIC_PATH .$thumbnailNew);

    				    //detail thumbnail;
    				    $detailThumbnail = str_replace('/cruise/', '/cruise/detail_thumbnail_', $thumbnail);
    				    $image->load(PUBLIC_PATH .$thumbnail);
    				    $image->resizeToWidth(366);
    				    $image->save(PUBLIC_PATH .$detailThumbnail);

					} catch (Exception $e) {
					}

					$r1 = $tbcruiseItineraryTour->safelyUpdate(array('detail_thumbnail' => $detailThumbnail), array('id=?' => $cruiseId));

	                $r = $tbArticle->safelyUpdate(array('thumbnail' 			=> $thumbnailNew),
	                					   		  array('reference_id = ?' 		=> $cruiseId,
	                					   		  		'reference_type = ?' 	=> M_DbTable_Article::REFERENCE_TYPE_CRUISE));

	                $this->_flashMessenger->addMessage($r ? self::$msgUpdateSuccess : self::$msgUpdateFailed);
           		    if($dThumbnail) {
    	        		$this->deletePhoto($dThumbnail['path']);
	                }
	                $this->refresh(array('id' => $cruiseId));
           		}
            }
        }
        $this->view->dataThumbnail 	= $dThumbnail;
    }

    public function galleryAction() {
        $rq = $this->_request;

        if($rq->getParam('act_delete_gallery')) {
            $this->_forward('delete-gallery', null, null);
        }

        $tbGallery = new M_DbTable_Gallery();
        $dThumbnail	= $tbGallery->getListActive()->query()->fetchAll();

        if ($rq->isPost()) {
       		if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
				$uploader = new Apps_Plugin_Upload_File();
				$uploader->setMaxQuantity(1)
						 ->setSubCategory(Apps_Plugin_Upload_File::CAT_GALLERY);
				$thumbnail = ($uploaded = $uploader->upload())
						 	 ? $uploaded['thumbnail']['uri']
						 	 : null;

				$tbGallery->safelyInsert(array('path' 			=> $thumbnail, 
											   'sorting_number' => $rq->getParam('sorting_number'),
											   'link_to' 		=> $rq->getParam('link_to'),
											   'caption'		=> $rq->getParam('caption')));

				//resize images
				try {
    				$image = new Apps_Plugin_ResizeImages();
    				$image->load(PUBLIC_PATH .$thumbnail);
    				$image->resize(958, 340);
    				$image->save(PUBLIC_PATH .$thumbnail);
				} catch (Exception $e) {
				    //Excetion here
				}

				$this->refresh();
       		}
        }
        $this->view->dataPhoto 	= $dThumbnail;
    }
    //delete gallery
    public function deleteGalleryAction() {
        $this->disallowBacktrack();
        $rq = $this->_request;
        $ids = $rq->getParam('item_checker');

        if(!$ids) {
            $this->_helper->redirector('gallery', null, null);
        } else {
            $tbGallery = new M_DbTable_Gallery();
            foreach($ids as $v) {
                $gallery = $tbGallery->fetchRow(array('id =?' => $v));
                if($gallery) {
                    $tbGallery->delete(array('id =?' => $v));
                    $this->deletePhoto($gallery['path']);
                }
            }
        }
        $this->_helper->redirector('gallery', null, null);
    }

    public function photoDeleteAction(){
        $this->disallowBacktrack();

    	// Only delete Photo type Not avatar, thumbnail.
        $rq = $this->_request;

        $hotelPhotoIds = $rq->getParam('item_checker');
        if(!$hotelPhotoIds) {
            $this->_helper->redirector('index', null, null, array('id' => $rq->getParam('id')));
        }
        $tbPhoto = new M_DbTable_Photo();

        $q = $this->_dbAdapter
                  ->select()
                  ->from('photo')
                  ->where('reference_type = ?', M_DbTable_Photo::REFERENCE_TYPE_HOTEL);

        $w = array();
        foreach($hotelPhotoIds as $hotelPhotoId) {
            $w[] = $this->_dbAdapter->quoteInto('id = ?', $hotelPhotoId);
        }
        $d = $q->where(implode(' OR ',$w))->query()->fetchAll();

        $tbPhoto->safelyDelete(implode(' OR ', $w));

        foreach ($d as $i => $info) {
            $this->deletePhoto($info['path']);
        }

        $this->_flashMessenger->addMessage(
            $d
            ? self::$msgDeleteSuccess
            : self::$msgDeleteError
        );
        $this->_helper->redirector('index', null, null, array('id' => $rq->getParam('id')));
    }


    public function deletePhoto($path) {
    	unlink(Apps_Plugin_Upload_File::getPath($path));
    }
}